import { View, Text, Swiper, SwiperItem, Image, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import NavigationBar from '@components/navigation-bar'
import { BasePage } from '@common/components/base-page'
import './index.scss'
import Jump from '@utils/jump'
import AppRoute from '@utils/route/index'
import IQRequest from '@common/iq-request/request'
import { setGlobalData, getAppData, getUuid, iQOOLog } from '@utils/tools'
import CryptoJS from 'crypto-js';
import CollectTool from '@components/collect-coins'


interface IProps { }
interface IState {
  model: string
  agreementStatus: boolean
  collectList: any
  eSportStatus: boolean
  ESportInfo: any
}
var timestamp = Date.parse(new Date()) / 1000;


const PVLogParams = {
  eventId: 'P774|1|1|7',
  params: {
    userId: '',
    page_name: '登录',
  },
};
export default class Login extends BasePage<IProps, IState> {

  constructor(props) {
    super(props);
    this.state = {
      model: '快捷登录',
      collectList: [],
      agreementStatus: false,
      eSportStatus: false,
      ESportInfo: {}
    }
  }
  pagesList: any = []
  componentWillMount() {
    let status = Taro.getStorageSync('agreementStatus')
    if (!!!status) {
      this.setState({
        agreementStatus: true
      })
    }
    this.pagesList = Taro.getCurrentPages()
  }
  ESportsInfo: any = ''
  componentDidMount() {
    console.log('wx.getAppBaseInfo', this.compareVersion(Taro.getAppBaseInfo().SDKVersion, '2.32.3'))
    if (Taro.getPrivacySetting) {
      Taro.getPrivacySetting({
        success(res) {
          console.log('触发本次事件的接口是：', res)
        }
      })
    } else {
      Taro.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
        success() {
          Jump.jump({
            url: AppRoute.APP.INDEX,
            type: 'switchTab'
          })
        }
      })
    }
  }
  // 判断版本号
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  }
  componentWillUnmount() {
    PVLogParams.eventId = 'P774|1|2|14'
    iQOOLog(PVLogParams, 'trace')
  }

  componentDidShow() {
    // this.compleatCode()
    // this.ESportsInfo = this.compleatCode()
    // let info = Taro.getLaunchOptionsSync()
    // Taro.showModal({
    //   content: JSON.stringify(info)
    // })
    this.ESportsInfo = Taro.getStorageSync('iQOOauthToken')
    // this.ESportsInfo = this.compleatCode('oV40X5ehZ84szapbIE74oLVIk1JQ')
  }


  componentDidHide() { }

  compleatCode = (openid) => {
    //加密密钥16位
    var encrypt_key = 'AzHxyRuTLG1cOY8p'; //长度必须为16位
    //加密向量16位
    var iv = '2h4tfIDqWAzk09dT';
    //要加密的数据
    var encrypt_string = '{"openid":' + '"' + openid + '"' + ',"requestTime":' + (Date.parse(new Date()) / 1000) + ',"requestId":"' + getUuid() + '"}';
    var authtoken = this.encrypt(encrypt_string, encrypt_key, iv);
    return authtoken
  }
  encrypt(str, key, iv) {
    //密钥16位
    var key = CryptoJS.enc.Utf8.parse(key);
    //加密向量16位
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(str, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
  }
  getUserInfo = (e) => {
    console.log(e)
    if (!!e?.detail?.rawData) {
      Taro.showToast({
        title: '登录中···',
        icon: 'loading',
      })
      IQRequest.VIVOLogin(e.detail.encryptedData, e.detail.iv).then((res: any) => {
        if (res.queryCode == 200) {
          Taro.showToast({
            title: '登录成功',
            icon: 'success'
          })
          // Taro.setStorageSync('Authorization', res.Data.accessToken)
          Taro.setStorageSync('userInfo', res.userInfo)
          // setGlobalData({
          //   Authorization: res.Data.accessToken
          // });
          setTimeout(() => {
            if (this.pagesList[this.pagesList.length - 2].route == 'modules/pages/login/index') {
              Jump.jump({
                url: AppRoute.APP.INDEX,
                type: 'reLaunch'
              })
            } else {
              Jump.back()
            }
          }, 2000);
        } else {
          Taro.showToast({
            title: '登录异常，请稍后重试',
            icon: 'none'
          })
        }
      }).catch((err) => {
        Taro.showToast({
          title: err.Message || '登录异常，请稍后重试',
          icon: 'none',
        })
      })
    } else {
      this.Toast('为了体验完整功能，请同意授权登陆', 'none')
    }
  }
  getPhoneNumber = (e) => {
    console.log('code---this.ESportsInfo', e, !!this.ESportsInfo)
    let _this = this
    if (!!!e?.detail?.encryptedData) {
      _this.Toast('为了体验完整功能，请同意授权手机号', 'none')
    } else {
      Taro.showToast({
        title: '绑定中···',
        icon: 'loading',
      })
      let FromData: any = {}
      FromData.encryptedData = e.detail.encryptedData
      FromData.iv = e.detail.iv
      FromData.randomNum = Taro.getStorageSync('randomNum')
      FromData.authtoken = _this.ESportsInfo

      Taro.login({
        success(res) {
          FromData.code = res.code
          console.log('FromData', FromData)
          IQRequest.IQOORequest(!!_this.ESportsInfo ? 'v3/users/esports/bind' : 'v3/users/vivo/mini/bind', FromData).then((response: any) => {
            if (response.Data.code == 30006) {
              _this.HidToast()
              Taro.showModal({
                title: '温馨提示',
                content: '抱歉检测到您微信绑定的vivo账号异常，请在电脑端，微信扫码登录vivo帐号重新进行绑定。',
                confirmText: '复制链接',
                success(result) {
                  if (result.confirm) {
                    Taro.setClipboardData({
                      data: 'https://open.weixin.qq.com/connect/qrconnect?response_type=code&appid=wx2198c66352420194&redirect_uri=https%3A%2F%2Fpassport.vivo.com.cn%2Fv3%2Fweb%2Flogin%2FwechatCallBack%3FisPc%3Dnull%26randomNum%3D&scope=snsapi_login&state=1663238910344',
                      success: function (res) {
                        Taro.getClipboardData({
                          success: function (res) {
                          }
                        })
                      }
                    })
                  }
                },
              })
              return false
            } else if (!!response.Data.code || response.Data.code == 30005) {
              _this.HidToast()
              Taro.showModal({
                title: '温馨提示',
                content: '此手机号已经绑定过微信号',
                showCancel: false,
                success(result) { },
              })
              return false
            }
            if (response.Code == -16008) {
              _this.setState({
                ESportInfo: response.Data.user,
                eSportStatus: true
              }, () => {
                _this.ESportsInfo = _this.compleatCode(response.Data.data.openid)
              })
              return
            }
            if (response?.Meta?.tips?.length > 0) {
              response.Meta.tips = response.Meta.tips.map(item => {
                return { ...item, status: false };
              });

              console.log('response', response.Meta.tips)
              this.setState({ collectList: response.Meta.tips }, () => { this.onInterViewShow() })
            }
            Taro.showToast({
              title: '绑定成功',
              icon: 'success'
            })
            setTimeout(() => {
              if (!!_this.ESportsInfo) {
                Taro.navigateBackMiniProgram({ extraData: { userId: response.Data.userId } })
              } else {
                if (!!Taro.getStorageSync('nextUrl')) {
                  Jump.jump({
                    url: Taro.getStorageSync('nextUrl'),
                    type: 'redirectTo',
                    query: {
                      sid: Taro.getStorageSync('nextShareId'),
                      pageType: 'yearType',
                    }
                  })
                  Taro.setStorageSync('nextUrl', '')
                } else {
                  if (_this.pagesList[_this.pagesList.length - 2].route == 'modules/pages/login/index') {
                    Jump.jump({
                      url: AppRoute.APP.INDEX,
                      type: 'reLaunch'
                    })
                  } else {
                    Jump.back()
                  }
                }
              }
            }, 2000);
            setGlobalData({
              Authorization: response.Data.accessToken
            });
            Taro.setStorageSync('Authorization', response.Data.accessToken)
            Taro.setStorageSync('userInfo', response.Data)
          })
        }
      })
    }

  }
  handleAgreePrivacyAuthorization = () => {
    console.log('同意了')
  }
  render() {
    let { model, agreementStatus, eSportStatus, ESportInfo, collectList } = this.state
    return (
      <>
        <View className='login-detail-modal'></View>
        {!!!agreementStatus && <View className='login-detail-modal-view'>
          <View className='login-detail-modal-view-close' onClick={() => {
            if (!!this.ESportsInfo) {
              Taro.navigateBackMiniProgram({ extraData: { userId: '' } })
            } else {
              Jump.jump({
                url: AppRoute.APP.INDEX,
                type: 'switchTab'
              })
            }

          }}></View>
          <View className='login-detail-modal-view-logo'></View>
          <View className='login-detail-modal-view-content'>为了更好地为您提供服务，请进行账号登录</View>
          <View className='flex align-center'>
            <Button className='login-detail-modal-view-button-fail login-detail-modal-view-button flex align-center justify-center' onClick={() => {
              Jump.jump({
                url: AppRoute.APP.INDEX,
                type: 'switchTab'
              })
            }}>暂不登录</Button>
            {
              model == '快捷登录' && <Button open-type="getUserInfo" onGetUserInfo={this.getUserInfo} className='login-detail-modal-view-button flex align-center justify-center'> {model}</Button>
            }
          </View >

        </View >}
        {
          collectList.map((item) => {
            return <>
              {
                item.status && <CollectTool isOpen={item.status} item={item}></CollectTool>
              }
            </>
          })
        }
        {
          agreementStatus && <>
            <View className="agreement-view">
              <View className="agreement-view-title">隐私申明</View>
              <View className="agreement-view-description"> 源流线报酷小程序可为您提供社区类的服务。服务提供过程中我们可能会收集使用vivo帐号信息、手机号、设备信息等，用于完成社区类服务；具体的信息收集规则与服务内容，请您在使用前认真查看<Text className='agreement-view-description-blue' onClick={() => {
                // Jump.jump({
                //   url: '/modules/pages/editor-info/index',
                // })
                Taro.setStorageSync('url', 'https://bbs.iqoo.com/privacy')
                Jump.jump({
                  url: AppRoute.MODULES.WEBVIEWPAGE
                })
              }}>《源流线报酷隐私政策》</Text>点击“同意”，即视为同意上述内容及隐私政策</View>
              <View className="agreement-view-confirm-view flex">
                <View className='agreement-view-confirm-view-button' onClick={() => {
                  if (!!this.ESportsInfo) {
                    Taro.navigateBackMiniProgram({ extraData: { userId: '' } })
                  } else {
                    if (this.$router.params.jumpWhite) {
                      Jump.jump({
                        url: AppRoute.APP.INDEX,
                        type: 'switchTab'
                      })
                    } else {
                      Jump.back()
                    }
                  }
                }}>取消</View>
                <View className='agreement-view-confirm-view-button' onClick={() => {
                  this.setState({
                    agreementStatus: false
                  }, () => {
                    Taro.setStorageSync('host', getAppData().host)
                    Taro.setStorageSync('agreementStatus', true)
                  })
                }}>
                  <button className='agreement-view-confirm-view-button-api' open-type="agreePrivacyAuthorization" bindagreeprivacyauthorization={this.handleAgreePrivacyAuthorization}>同意</button>
                  同意</View>
              </View>
            </View>
          </>
        }

      </>
    )
  }
}
